<?php

namespace App\Admin\Eloquent;
use App\Admin\Eloquent\Code;
use App\Admin\Eloquent\User;
use App\Eloquent\User as PUser;
use App\Admin\Eloquent\GiftAttr;
use App\Admin\Eloquent\ProjectsUser;
use App\Eloquent\TradeRecords;
use App\Admin\Eloquent\GiftReceive;
use App\Exceptions\BusinessException;
use Router;
use CreateHostingCollectTrade;
use CreateSingleHostingPayTrade;
use CreateBatchHostingPayTrade;
use Log;

class GiftActivity extends Model
{
    /**
     * 实例化模型时, 可批量赋值属性白名单
     *
     * @var array
     */
    protected $fillable = [
        'name', 'action','cate_id', 'type_id','total_money', 'begin_time', 'end_time','used_rule',
        'used_rule_money','grant_rule','effect_time1','effect_time2','effect_day','status'
    ];
    public $timestamps = false;
    
    public function __constract(){
        parent::__constract();
    }
    /**
     * 模糊查询红包活动记录
     *
     * @param array $options
     * @param int $pagesize
     * @return mixed
     */
    public static function paging_query(array $options, int $pagesize = 15)
    {

        $query = GiftActivity::query();

        //判断参数 追加查询条件
        if(isset($options['search']) && !empty($options['search'])){
            $condition = '%'.$options['search'].'%';
            $query = $query->where('name', 'like',$condition);
        }

        $query->orderBy('status','asc');

        return $query->paginate($pagesize);
    }
    /**
     * 获取活动类型
     */
    public static function getTypes(){
        $code=new Code();
        return $code->where("type_id","=","gift_activity_type")->get();
    }
    /**
     * 获取活动分类
     */
    public static function getCates(){
        $code=new Code();
        return $code->where("type_id","=","gift_activity_cate")->get();
    }
    /**
     * 获取红包使用规则
     */
    public static function getRules(){
        $code=new Code();
        return $code->where("type_id","=","gift_money_used_rule")->get();
    }
    /**
     * 获取红包发放规则
     */
    public static function getGrants(){
        $code=new Code();
        return $code->where("type_id","=","gift_grant_rule")->get();
    }
    /**
     * 获取可定向发放的红包活动
     */
    public static function getActivities(){
    	return GiftActivity::where('grant_rule','=','gift_grant_rule_4')->where('status','=',1)->get();
    }
    /**
     * 判断红包活动是否可用
     */
    public static function checkActivity($id,$money){
    	$activity=GiftActivity::find($id);
    	if($activity->status!=1){
    		throw new BusinessException("红包活动未启用或已结束");
    	}
    	if(time()>strtotime($activity->end_time)){
    		throw new BusinessException("红包活动已结束");
    	}
    	if($money+$activity->used_money>$activity->total_money){
    		throw new BusinessException("红包活动金额不足");
    	}
    }
    /**
     * 自动更新红包活动状态
     * @return [type] [description]
     */
    public static function updateActivity(){
    	//更新红包活动
        GiftActivity::where('end_time','<',date('Y-m-d H:i:s'))->update(['status'=>4]);
        //更新红包记录状态
        GiftReceive::where('end_time','<',date('Y-m-d H:i:s'))->where('status',0)->update(['status'=>2]);
    }

    /**
     * 发放生日红包
     * @return [type] [description]
     */
    public static function birthGift(){
        $rule='gift_grant_rule_2';
        $user=PUser::user();
        if(!$user->userInfo || !$user->isSetRealName()){return false;}
        $activity=GiftActivity::where('begin_time','<',date('Y-m-d H:i:s'))
        ->where('grant_rule','=',$rule)
        ->where('status','=',1)
        ->first();
        $id_card = $user->UserInfo->id_card;
        if(!empty($id_card) && !empty($activity)){
            $year=date('Y');
            $birthday=strlen($id_card)==15 ? ('19' . substr($id_card, 10, 4)) : substr($id_card, 10, 4);
            $month=substr($birthday,0,2);
            $date=substr($birthday,2,2);
            $time=strtotime($year.'-'.$month.'-'.$date);
            if(strtotime($activity->begin_time)<$time && strtotime($activity->end_time)>$time){
                $count=GiftReceive::where('activity_id','=',$activity->id)->where('input_time','=',$year.'-'.$month.'-'.$date)
                ->where('user_id','=',$user->id)->count();
                if($count==0){
                    GiftActivity::sendGift($rule,$user->id,$year.'-'.$month.'-'.$date);
                }
            }
        }
    }
    /**
     * 发放红包(需要开启事物)
     * @param  [type] $rule    发放规则 code
     * @param  [type] $user_id 发放用户 
     * @param  [type] $time          发放时间 Y-m-d H:i:s
     * @param  [type] $project_money 金额(投资满额时的金额)
     * @return [type]          array('status'=>状态码,'msg'=>错误信息,'data'=>红包记录)
     */
    public static function sendGift($rule,$user_id,$time=null,$project_money=0,$cate=null){
        $result=array('status'=>0,'msg'=>'');
        //如果为激活红包(已设置支付密码)
        if($rule=='gift_grant_rule_7'){
            //发放注册的现金红包
            $register_gift=GiftReceive::join('gift_activities','gift_activities.id','=','gift_receives.activity_id')
            ->where('gift_activities.type_id','gift_activity_type_2')
            ->where('gift_activities.grant_rule','gift_grant_rule_1')
            ->where('gift_receives.user_id',$user_id)
            ->where('gift_receives.status',0)->first();
            if(!empty($register_gift)){
              GiftActivity::sendMoney([$user_id],$register_gift->money);
            }
            //仅发放给有投资记录的用户
            if(ProjectsUser::where('user_id',$user_id)->count()==0){
              $result=array('status'=>3,'msg'=>'用户无投资记录');
              return $result;
            }
        }
        //如果为注册红包
        if($rule=='gift_grant_rule_1'){
	        $result=GiftActivity::sendRegister($user_id,$time,$project_money);
	        return $result;
        }
        $user=User::find($user_id);
        if(empty($user)){
            $result=array('status'=>5,'msg'=>'用户不存在');
            return $result;
        }
        if(empty($time)){$time=date('Y-m-d H:i:s');}
        //红包活动唯一
        $activity=GiftActivity::where('begin_time','<',date('Y-m-d H:i:s'))->where('grant_rule','=',$rule)->where('status',1);
        if($cate!==null){
            $activity=$activity->where('cate_id',$cate);
        }
        $activity=$activity->first();
        if(empty($activity)){
            $result['status']=2;
            $result['msg']='活动已结束';
            return $result;
        }
        //获取红包的发放金额
        $money=$activity->getGrantMoney($project_money);
        if($money==0){
            $result['status']=4;
            $result['msg']='不满足红包发放的规则';
            return $result;
        }
        //判断红包余额
        if($money+$activity->used_money>$activity->total_money){
            $result['status']=1;
            $result['msg']='活动余额不足';
            return $result;
        }

        //红包有效时间
        if(!empty($activity->effect_day)){
            $begin_time=date('Y-m-d H:i:s');
            $end_time=date('Y-m-d H:i:s',strtotime('+'.$activity->effect_day.' day'));
        }else{
            $begin_time=$activity->effect_time1;
            $end_time=$activity->effect_time2;
        }
        $data=array('activity_type'=>$activity->type_id,'activity_id'=>$activity->id,'begin_time'=>$begin_time,
            'user_id'=>$user_id,'money'=>$money,'input_time'=>$time);
        //如果是现金红包,无有效期并默认使用时间
        if($activity->type_id=='gift_activity_type_2'){
            $data['end_time']=null;
            //如果用户未设置支付密码,现金红包将在设置支付密码后发放
            if($user->userInfo->is_set_pay_password){
                $data['use_time']=$time;
                $data['status']=1;
            }else{
                $data['status']=0;
            }
        }else{
            $data['end_time']=$end_time;
        }
        //更新红包活动金额
        $activity->increment('used_money',$money);
        //添加发放记录
        $gift_receive=new GiftReceive($data);
        $gift_receive->save();
        //发放现金红包
        if($activity->type_id=='gift_activity_type_2' && $user->userInfo->is_set_pay_password){
            GiftActivity::sendMoney([$user_id],$money,$gift_receive->id);
        }
        //金额发放完成，修改活动状态
        if($money+$activity->used_money==$activity->total_money){
            $activity->update(['status'=>2]);
        }
        $result['data']=$data;
        Log::info($gift_receive->id.'红包金额'.$money);
        return $result;
    }

    public static function sendRegister($user_id,$time=null,$project_money=0){
        $result=array('status'=>0,'msg'=>'','money'=>0);
        $user=User::find($user_id);
        if(empty($time)){$time=date('Y-m-d H:i:s');}
        $activities=GiftActivity::where('begin_time','<',date('Y-m-d H:i:s'))->where('grant_rule','gift_grant_rule_1')->where('status',1)->get();
        if(empty($activities)){
            $result['status']=2;
            $result['msg']='活动已结束';
            return $result;
        }

        foreach ($activities as $activity) {
        	$money=$activity->getGrantMoney($project_money);
        	if($money==0){
        	    $result['status']=4;
        	    $result['msg']='不满足红包发放的规则';
        	}
        	//判断红包余额
        	if($money+$activity->used_money>$activity->total_money){
        	    $result['status']=1;
        	    $result['msg']='活动余额不足';
        	}

        	//红包有效时间
        	if(!empty($activity->effect_day)){
        	    $begin_time=date('Y-m-d H:i:s');
        	    $end_time=date('Y-m-d H:i:s',strtotime('+'.$activity->effect_day.' day'));
        	}else{
        	    $begin_time=$activity->effect_time1;
        	    $end_time=$activity->effect_time2;
        	}
        	$data=array('activity_type'=>$activity->type_id,'activity_id'=>$activity->id,'begin_time'=>$begin_time,
        	    'user_id'=>$user_id,'money'=>$money,'input_time'=>$time);
        	//如果是现金红包,无有效期并默认使用时间
        	if($activity->type_id=='gift_activity_type_2'){
        	    $data['end_time']=null;
        	    //如果用户未设置支付密码,现金红包将在设置支付密码后发放
        	    if($user->userInfo->is_set_pay_password){
        	        $data['use_time']=$time;
        	        $data['status']=1;
        	    }else{
        	        $data['status']=0;
        	    }
        	}else{
        	    $data['end_time']=$end_time;
        	}
        	//更新红包活动金额
        	$activity->increment('used_money',$money);
        	//添加发放记录
        	$gift_receive=new GiftReceive($data);
        	$gift_receive->save();
        	//发放现金红包
        	if($activity->type_id=='gift_activity_type_2' && $user->userInfo->is_set_pay_password){
        	    GiftActivity::sendMoney([$user_id],$money,$gift_receive->id);
        	}
        	//金额发放完成，修改活动状态
        	if($money+$activity->used_money==$activity->total_money){
        	    $activity->update(['status'=>2]);
        	}
            Log::info('注册'.$gift_receive->id.'红包金额'.$money);
            $result['money']+=$money;
        }
        return $result;
    }

    /**
     * 发送现金红包
     * @param  array $user_ids 用户编号
     * @param  int   $money    发放金额
     * @return [type]           [description]
     */
    public static function sendMoney($user_ids,$money,$gift=0){
        //sian用户ID,已设置支付密码的用户
        $identity_ids=User::join('user_info','user_info.user_id','=','users.id')->whereIn('users.id',$user_ids)->where('user_info.is_set_pay_password',1)->lists('users.identity_id')->toArray();
        $data=[
            'out_trade_no'=>createSn(),
            'out_trade_code'=>'1001',
            'summary'=>'代收发放现金红包总金额',
            'payer_id'=>config('sinapay.payer_id'),
            'payer_identity_type'=>config('sinapay.payer_type'),
            'pay_method'=>'balance^'.count($user_ids)*$money.'^'.config('sinapay.gift_payer_account'),
        ];
        $result1=json_decode(CreateHostingCollectTrade::send($data),true);
        if($result1['response_code']!='APPLY_SUCCESS'){abort(600,$result1['response_message']);}
        //批量代付
        $trade_list='';
        $trade_data=array();
        foreach ($identity_ids as $key=>$value) {
            $sn=createSn();
            $str=$sn.'~'.config('sinapay.payer_id').'~'.config('sinapay.payer_type').'~'.config('sinapay.gift_payer_account').'~'.$money.'~'.config('sinapay.payer_id').'^'.config('sinapay.payer_type').'^'.config('sinapay.gift_payer_account').'^'.$value.'^UID^SAVING_POT^'.$money.'~现金红包';
            if($key!=0){$str='$'.$str;}
            $trade_list.=$str;
            $trade_data[]=array('type'=>6,'sn'=>$sn,'pay_user'=>3,'receive_user'=>$user_ids[$key],'money'=>$money,'created_at'=>date('Y-m-d H:i:s'),'gift'=>$gift);
        }
        $sn1=createSn();
        $data=[
            'out_pay_no'=>$sn1,
            'out_trade_code'=>'2001',
            'trade_list'=>$trade_list,
            'notify_method'=>'single_notify',
            'notify_url'=>config('sinapay.notify_url').'/return/sendGift',
        ];
        $result2=CreateBatchHostingPayTrade::send($data);
        if($result2['response_code']!='APPLY_SUCCESS'){abort(600,$result2['response_message']);}
        //添加流水记录
        return TradeRecords::insert($trade_data);
    }

    public function type()
    {
    	return Code::findByCodeAndTypeId($this->type_id, 'gift_activity_type');
    }
    public function cate()
    {
        return Code::findByCodeAndTypeId($this->cate_id, 'gift_activity_cate');
    }
    public function grant()
    {
        return Code::findByCodeAndTypeId($this->grant_rule, 'gift_grant_rule');
    }
    public function used()
    {
        return Code::findByCodeAndTypeId($this->used_rule, 'gift_money_used_rule');
    }
    public function status()
    {
        return Code::findByCodeAndTypeId('gift_activity_status_'.$this->status, 'gift_activity_status');
    }
    /**
     * 获取红包的发放规则
     * @return int 1:送xx,2:投xx,送xx,4:定向
     */
    public function returnRule(){
        $rules=array(
            1=>array('gift_grant_rule_1','gift_grant_rule_2','gift_grant_rule_5','gift_grant_rule_6','gift_grant_rule_7'),//送XX
            3=>array('gift_grant_rule_3','gift_grant_rule_8'),//投xx,送xx
            4=>array('gift_grant_rule_4'),//定向
        );
        $rule=0;
        foreach($rules as $key=>$item){
            if(in_array($this->grant_rule,$item)){
                $rule=$key;
                break;
            }
        }
        return $rule;
    }
    /**
     * 红包活动发放规则的得到金额
     * @param  [type] $money [description]
     * @return [type]        [description]
     */
    public function getGrantMoney($money){
      $rule=$this->returnRule();
      $attr=GiftAttr::where('activity_id',$this->id)->lists('value','name')->toArray();
      $gift=0;
      if($rule==1){
        $gift=$attr['son_0'];
      }
      if($rule==3){
        foreach ($attr as $key=>$value) {
          if(preg_match('/tou/',$key) && $money>$value){
            $exp=explode('_',$key);
            $gift=$attr['son_'.$exp[1]];
          }
        }
        if(isset($attr['auto']) && $gift>0){
          $gift=floor($money/$attr['tou_0'])*$attr['son_0'];
        }
      }
      return $gift;
    }
}